import React from 'react';
import {
    Card,
    Table,
    Divider,
    Modal,
    Button,
    Form,
    Input,
    Radio,
    Icon,
    message,
    DatePicker,
    Pagination,
    Upload,
    Select,
    Spin,
    Popover,
    AutoComplete
} from 'antd';
import {NavLink} from 'react-router-dom';
import moment from 'moment';
import ResizeableTitle from './../../../utils/resizeableTitle';
import Utils from './../../../utils/utils';
import './../../../style/style.css';
import Axios from "../../../axios";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const TextArea = Input.TextArea;

export default class UserCheck extends React.Component {
    state = {
        columns: [{
            title: '考核标题',
            dataIndex: 'title',
            width: 200,
        }, {
            title: '编号',
            dataIndex: 'examineNo',
            width: 150,
        }, {
            title: '考核内容',
            dataIndex: 'content',
            width: 200,
        }, {
            title: '考核类型',
            dataIndex: 'type',
            width: 150,
            render(type){
                let config = {
                    "PRE_JOB":"岗前考核",
                    "ANNUAL":"年度考核",
                }
                return config[type];
            }
        }, {
            title: '用户',
            dataIndex: 'userName',
            width: 150,
        }, {
            title: '真实姓名',
            dataIndex: 'realname',
            width: 150,
        }, {
            title: '考核时间',
            dataIndex: 'examineTime',
            width: 200,
        }, {
            title: '考核方式',
            dataIndex: 'examineMode',
            width: 150,
        }, {
            title: '考核描述',
            dataIndex: 'description',
            width: 150,
        }, {
            title: '考核结果',
            dataIndex: 'result',
            width: 150,
        },{
            title: '状态',
            dataIndex: 'state',
            width: 100,
            render: (text, record, index) => (
                <span>
                    {record.state == "VALID" ? <span className="txt-success">审批通过</span> : ''}
                    {record.state == "INVALID" ? <span className="txt-danger">审批拒绝</span> : ''}
                    {record.state == "DISABLE" ? <span className="txt-danger">禁用的</span> : ''}
                    {record.state == "DELETE" ? <span className="txt-danger">删除的</span> : ''}
                    {record.state == "WAIT_AUDIT" ? <span className="txt-danger">待审核</span> : ''}
                    {record.state == "UNDER_REVIEW" ? <span className="txt-danger">审核中</span> : ''}
                </span>
            )
        }, {
            title: '操作',
            key: 'action',
            render: (text, record, index) => (
                <span>
                    <NavLink className="btn-txt-primary"
                             to={`/organMember/user/userCheckDetails/${record.id}`}>查看详情</NavLink>
                    {record.state == "WAIT_AUDIT" ?
                        <span>
                            <Divider type="vertical" />
                            <a href="javascript:;" onClick={() => this.handleAgainApprove(record)} className="btn-txt-primary">再次审批</a>
                            <Divider type="vertical"/>
                            <a onClick={() => this.handleDel(record)} className="btn-txt-danger">删除</a>
                        </span>
                        : ''
                    }
                    {record.state == "INVALID" ?
                        <span>
                            <Divider type="vertical"/>
                            <a onClick={() => this.handleDel(record)} className="btn-txt-danger">删除</a>
                        </span>
                        : ''
                    }
                </span>
            ),
        }],
        createModal: {
            visible: false,
            confirmLoading: false,
        },
    };
    initParams = {
        max: 10,
        realname: '',
        page: 1,
        state: '',
        type:""
    }

    componentWillMount() {
        let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
        this.listRequest(params);
        this.userRequest();//所有用户请求
        this.deptRequest();//所有部门请求
        this.checkMethodsRequest();//快搜-考核方式
    }

    //搜索
    handleFilter = (fieldsValue) => {
        const values = {
            ...fieldsValue,
        };
        console.log(values);
        this.initParams = {
            ...this.initParams,
            ...values,
            page: 1
        }
        let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
        this.listRequest(params)
    }
    //删除
    handleDel = (record) => {
        Modal.confirm({
            title: '确认删除？',
            content: <div>
                <div>删除后数据不可恢复！</div>
                <div className="txt-danger">确认删除？</div>
            </div>,
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                console.log(record.id)
                let params = {
                    id: record.id,
                }
                this.delRequest(params);
            }
        })
    }
    //创建人员考核 弹窗
    handleCreate = (record) => {
        this.setState({
            createModal: {
                ...this.state.createModal,
                visible: true,
            }
        })
    }
    //创建人员考核 提交
    handleCreateSubmit = () => {
        const _form = this.createForm.props.form;
        _form.validateFields((err, values) => {
            console.log(values);
            if (err) {
                return;
            }
            console.log(values);
            values.department =  values.department?values.department.label:"";
            values.examineTime = values.examineTime?moment(values.examineTime).format('YYYY-MM-DD HH:mm:ss'):"";
            values.userId = values.userIdName.key;
            values.userName = values.userIdName.label;
            delete values.userIdName;
            let param = Utils.FilterParam(values);
            console.log(param)
            //TODO 2019-01-11 19:55:51文件上传还未完成
            this.createRequest(param);
        });
    }
    //再次提交审批
    handleAgainApprove = (record)=>{
        Modal.confirm({
            title: '确认提交审批？',
            content: <div>
                <div className="txt-danger">确认提交审批？</div>
            </div>,
            okText:'确认',
            cancelText:'取消',
            onOk:()=>{
                console.log(record.id)
                let params = {
                    id:record.id,
                }
                this.approveRequest(params);
            }
        })
    }

    /*培训后考核列表请求*/
    listRequest = (params) => {
        let _this = this;
        this.setState({
            loading: true,
            loadingTxt: '加载中...'
        })
        Axios.dataRequest({
            block: '/hr',
            url: '/userExamine',
            params: params,
        }).then((data) => {
            console.log(data)
            let page = data.page;
            let dataSource = data.data;
            dataSource.map((item) => {
                item.key = item.id;
                return item;
            })
            this.setState({
                loading: false,
                dataSource,
                pagination: Utils.pagination(page, (current) => {
                    _this.initParams.page = current;
                    let params = this.initParams;
                    _this.listRequest(params);
                }, (current, pageSize) => {
                    _this.initParams.page = current;
                    _this.initParams.max = pageSize;
                    let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                    _this.listRequest(params);
                })
            })
        }).catch((error) => {
            this.setState({loading: false})
            console.log(error);
        })
    }
    /*删除请求*/
    delRequest = (params) => {
        this.setState({
            loading: true,
            loadingTxt: '删除中...'
        })
        Axios.delRequest({
            block: '/hr',
            url: '/userExamine',
            params: params,
        }).then((data) => {
            console.log(data);
            this.setState({loading: false})
            message.success('删除成功！', 2, () => {
            });
            let _params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
            this.listRequest(_params);
        }).catch((error) => {
            this.setState({loading: false})
            console.log(error);
        })
    }
    /*创建用户考核请求*/
    createRequest = (params) => {
        this.setState({
            createModal: {
                ...this.state.createModal,
                confirmLoading: true,
            }
        })
        Axios.formRequest({
            block: '/hr',
            url: '/userExamine',
            params: params,
        }).then((data) => {
            console.log(data)
            this.setState({
                createModal: {
                    ...this.state.createModal,
                    visible: false,
                    confirmLoading: false,
                }
            })
            message.success('创建用户考核成功！', 2);
            window.location.reload()
            //let _params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
            //this.listRequest(_params);
        }).catch((error) => {
            console.log(error);
            this.setState({
                createModal: {
                    ...this.state.createModal,
                    confirmLoading: false,
                }
            })
        })
    }
    /*提交审批请求*/
    approveRequest = (params)=>{
        this.setState({
            loading:true,
            loadingTxt:'提交审批中...'
        })
        Axios.formRequest({
            block:'/hr',
            url:'/userExamine/approval',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                loading:false,
            })
            message.success('提交审批成功！',2,()=>{
                //this.listRequest(_this.initParams);
            });
            window.location.reload();
        }).catch((error)=>{
            this.setState({
                loading:false,
            })
            console.log(error);
        })
    }
    /*所有用户请求*/
    userRequest = () => {
        Axios.dataRequest({
            block: '/hr',
            url: '/user/allUserSmallInfos',
            params: "",
        }).then((data) => {
            //console.log(data)
            let users = data.data;
            /*id name userNo*/
            this.setState({
                users,
            })
        }).catch((error) => {
            console.log(error);
        })
    }
    /*所有部门请求*/
    deptRequest = () => {
        Axios.dataRequest({
            block: '/hr',
            url: '/department',
            params: "",
        }).then((data) => {
            //console.log(data)
            let depts = data.data;
            this.setState({
                depts,
            })
        }).catch((error) => {
            console.log(error);
        })
    }
    /*快速搜索-考核方式*/
    checkMethodsRequest = () => {
        let params = {
            key: '用户考核方式'
        }
        Axios.dataRequest({
            block: '/setting',
            url: '/quickSelect/query',
            params: params,
        }).then((data) => {
           // console.log(data)
            let checkMethods = data.data;
            this.setState({
                checkMethods
            })
        }).catch((error) => {
            console.log(error);
        })
    }
    //伸缩列
    components = {
        header: {
            cell: ResizeableTitle
        },
    };
    handleResize = index => (e, {size}) => {
        this.setState(({columns}) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return {columns: nextColumns};
        });
    };

    render() {
        const columns = this.state.columns.map((col, index) => ({
            ...col,
            onHeaderCell: column => ({
                width: column.width,
                onResize: this.handleResize(index),
            }),
        }));
        return (
            <div className="tab-list-box">
                <Spin spinning={this.state.loading} size="large" tip={this.state.loadingTxt}>
                    <Card
                        title="用户考核列表"
                        bordered={false}>
                        <div style={{textAlign: 'right', marginBottom: 15}}>
                            <div className="filter-box" style={{marginBottom: 15}}>
                                <FilterForm filterSubmit={(fieldsValue) => {
                                    this.handleFilter(fieldsValue)
                                }}/>
                                <Button type="primary" icon="plus" onClick={this.handleCreate}>创建用户考核</Button>
                            </div>
                        </div>
                        <Table
                            bordered
                            components={this.components}
                            columns={columns}
                            dataSource={this.state.dataSource}
                            pagination={this.state.pagination}
                        />
                    </Card>
                    <Modal title="创建用户考核"
                           width={850}
                           visible={this.state.createModal.visible}
                           onOk={this.handleCreateSubmit}
                           okText="确定"
                           confirmLoading={this.state.createModal.confirmLoading}
                           destroyOnClose={true}
                           onCancel={() => {
                               this.setState({
                                   createModal: {
                                       visible: false
                                   }
                               })
                           }}
                    >
                        <CreateForm
                            users={this.state.users}
                            depts={this.state.depts}
                            checkMethods={this.state.checkMethods}
                            wrappedComponentRef={(createForm) => {
                                this.createForm = createForm;
                            }}/>
                    </Modal>
                </Spin>
            </div>
        );
    }

}

//创建人员考核表单
class CreateForm extends React.Component {
    state = {
        checkMethods: []
    }
    componentWillMount(){
        this.getNoRequest();
    }
    handleUserChange = (val)=>{
        console.log(val)
        if (val){
            let params = {
                id:val.key
            }
            this.userDetailsRequest(params);
        }
    }
    //快速搜索匹配
    handleSearch = (value) => {
        let checkMethods = this.props.checkMethods;
        this.setState({
            checkMethods: !value ? [] : this.filter(value, checkMethods),
        });
    }
    filter = (str, arr) => {
        let result = []
        arr.map((item) => {
            if (item.text.toLowerCase().indexOf(str.toLowerCase()) >= 0) {
                result.push(item.text)
            }
        })
        return result
    }

    /*查询用户详情请求*/
    userDetailsRequest = (params)=>{
        this.setState({
            loading:true,
            loadingTxt:'用户信息拉取中...'
        })
        Axios.dataRequest({
            block:'/hr',
            url:'/user/detail',
            params:params,
        }).then((data)=>{
            console.log(data)
            let userDetails = data.data;
            let jobTitle = userDetails.jobTitle;    //职称
            let position = userDetails.position;    //职位
            let jobs = userDetails.jobs;    //岗位
            let depts = userDetails.depts;    //部门
            let realname = userDetails.realname;    //真实姓名
            this.setState({
                loading:false,
                userDetails,
                jobTitle,
                position,
                jobs,
                depts,
                realname,
            })
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }
    /*获取用户编号请求*/
    getNoRequest = ()=>{
        this.setState({
            loading:true,
            loadingTxt:'用户信息拉取中...'
        })
        let params = {
            key:'userCheck_no'
        }
        Axios.dataRequest({
            block:'/setting',
            url:'/objectNo/nextNo',
            params:params,
        }).then((data)=>{
            console.log(data)
            let No = data.data;
            this.setState({
                loading:false,
                No
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                loading:false,
            })
        })
    }
    render() {
        const {getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 16}
        };
        const checkMethods = this.state.checkMethods;
        const users = this.props.users || [];
        const depts = this.props.depts || [];
        const userOptions = users.map((item) => {
            return <Option key={item.id}>{item.name}</Option>;
        });
        const deptOptions = depts.map((item) => {
            return <Option key={item.id}>{item.name}</Option>;
        });
        return (
            <Spin spinning={this.state.loading} size="large" tip={this.state.loadingTxt}>
                <div className="layout-form">
                    <Form className="left-div">
                        <FormItem label="考核标题" {...formItemLayout}>
                            {
                                getFieldDecorator('title', {
                                    rules: [{required: true, message: '请填写考核标题!'}],
                                })(
                                    <Input type="text" placeholder="考核标题"/>
                                )
                            }
                        </FormItem>
                        <FormItem label="考核编号" {...formItemLayout}>
                            {
                                getFieldDecorator('examineNo', {
                                    rules: [{required: true, message: '请填写考核编号!'}],
                                    initialValue:this.state.No
                                })(
                                    <Input type="text" placeholder="考核编号"/>
                                )
                            }
                        </FormItem>
                        <FormItem label="考核内容" {...formItemLayout}>
                            {
                                getFieldDecorator('content', {
                                    rules: [{required: true, message: '请填写考核内容!'}],
                                })(
                                    <TextArea placeholder="考核编号" autosize/>
                                )
                            }
                        </FormItem>
                        <FormItem label="考核类型" {...formItemLayout}>
                            {
                                getFieldDecorator('type', {
                                    rules: [{required: true, message: '请选择考核类型!'}],
                                })(
                                    <Select placeholder="考核类型" style={{width: 100}}>
                                        <Option value="PRE_JOB">岗前考核</Option>
                                        <Option value="ANNUAL">年度考核</Option>
                                    </Select>
                                )
                            }
                        </FormItem>
                        <FormItem label="用户" {...formItemLayout}>
                            {
                                getFieldDecorator('userIdName', {
                                    rules: [{required: true, message: '请选择用户!'}],
                                })(
                                    <Select
                                        placeholder="用户"
                                        labelInValue
                                        style={{minWidth: 160}}
                                        showSearch
                                        onChange={this.handleUserChange}
                                        optionFilterProp="children"
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                    >
                                        {userOptions}
                                    </Select>
                                )
                            }
                        </FormItem>
                        <FormItem label="部门" {...formItemLayout}>
                            {
                                getFieldDecorator('department', {})(
                                    <Select
                                        placeholder="部门"
                                        labelInValue
                                        style={{minWidth: 160}}
                                        showSearch
                                        optionFilterProp="children"
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                    >
                                        {deptOptions}
                                    </Select>
                                )
                            }
                        </FormItem>
                        <FormItem label="真实姓名" {...formItemLayout}>
                            {
                                getFieldDecorator('realname', {
                                    initialValue:this.state.realname
                                })(
                                    <Input type="text" placeholder="真实姓名"/>
                                )
                            }
                        </FormItem>
                        <FormItem label="岗位" {...formItemLayout}>
                            {
                                getFieldDecorator('post', {
                                    initialValue:this.state.jobs
                                })(
                                    <Input type="text" placeholder="岗位"/>
                                )
                            }
                        </FormItem>
                    </Form>
                    <Form className="right-div">
                        <FormItem label="职务" {...formItemLayout}>
                            {
                                getFieldDecorator('position', {
                                    initialValue:this.state.position
                                })(
                                    <Input type="text" placeholder="职务"/>
                                )
                            }
                        </FormItem>
                        <FormItem label="职称" {...formItemLayout}>
                            {
                                getFieldDecorator('jobTitle', {
                                    initialValue:this.state.jobTitle
                                })(
                                    <Input type="text" placeholder="职称"/>
                                )
                            }
                        </FormItem>
                        <FormItem label="考核时间" {...formItemLayout}>
                            {
                                getFieldDecorator('examineTime', {})(
                                    <DatePicker format="YYYY-MM-DD HH:mm:ss" showTime={true} placholder="考核时间"/>
                                )
                            }
                        </FormItem>
                        <FormItem label="考核方式" {...formItemLayout}>
                            {
                                getFieldDecorator('examineMode', {})(
                                    <AutoComplete
                                        dataSource={checkMethods}
                                        /*onSelect={onSelect}*/
                                        onSearch={this.handleSearch}
                                        placeholder="考核方式"
                                    />
                                )
                            }
                        </FormItem>
                        <FormItem label="考核描述" {...formItemLayout}>
                            {
                                getFieldDecorator('description', {})(
                                    <TextArea placeholder="考核描述" autosize/>
                                )
                            }
                        </FormItem>
                        <FormItem label="考核结果" {...formItemLayout}>
                            {
                                getFieldDecorator('result', {})(
                                    <TextArea placeholder="考核结果" autosize/>
                                )
                            }
                        </FormItem>
                        <FormItem label="附件编号列表" {...formItemLayout}>
                            {
                                getFieldDecorator('attachments', {})(
                                    <TextArea placeholder="附件编号列表" autosize/>
                                )
                            }
                        </FormItem>
                    </Form>
                </div>
            </Spin>

        );
    }
}
CreateForm = Form.create({})(CreateForm);

//搜索表单
class FilterForm extends React.Component {
    handleFilterSubmit = () => {
        let fieldsValue = this.props.form.getFieldsValue();
        this.props.filterSubmit(fieldsValue);
    }
    //重置
    reset = () => {
        this.props.form.resetFields();
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <Form layout="inline">
                <FormItem label="状态">
                    {
                        getFieldDecorator('state', {
                            initialValue: ""
                        })(
                            <Select placeholder="用户状态" style={{minWidth: 100}}>
                                <Option key="ALL" value="">全部</Option>
                                <Option key="VALID" value="VALID">审批通过</Option>
                                <Option key="INACTIVE" value="INACTIVE">审批拒绝</Option>
                                <Option key="WAIT_AUDIT" value="WAIT_AUDIT">待审核</Option>
                                <Option key="UNDER_REVIEW" value="UNDER_REVIEW">审核中</Option>
                            </Select>
                        )
                    }
                </FormItem>
                <FormItem label="类型">
                    {
                        getFieldDecorator('type', {
                            initialValue: ""
                        })(
                            <Select placeholder="类型" style={{minWidth: 100}}>
                                <Option key="ALL" value="">全部</Option>
                                <Option key="PRE_JOB" value="PRE_JOB">岗前考核</Option>
                                <Option key="ANNUAL" value="ANNUAL">年度考核</Option>
                            </Select>
                        )
                    }
                </FormItem>
                <FormItem label="关键词">
                    {
                        getFieldDecorator('keywords', {})(
                            <Input type="text" placeholder="关键词"/>
                        )
                    }
                </FormItem>
                <FormItem>
                    <Button type="primary" style={{margin: '0 20px'}} onClick={this.handleFilterSubmit}>查询</Button>
                    <Button onClick={this.reset}>重置</Button>
                </FormItem>
            </Form>
        );
    }
}

FilterForm = Form.create({})(FilterForm);